// AuthViewModel.java
package com.example.app3_1;

import android.app.Application;
import android.content.SharedPreferences;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import org.json.JSONObject;

public class AuthViewModel extends AndroidViewModel {
    private MutableLiveData<String> loginResult = new MutableLiveData<>();
    private MutableLiveData<String> registerResult = new MutableLiveData<>();
    private MutableLiveData<String> autoLoginResult = new MutableLiveData<>();
    private SharedPreferences sharedPreferences;

    public AuthViewModel(Application application) {
        super(application);
        sharedPreferences = application.getSharedPreferences("UserData", 0);
    }

    public MutableLiveData<String> getLoginResult() {
        return loginResult;
    }

    public MutableLiveData<String> getRegisterResult() {
        return registerResult;
    }

    public MutableLiveData<String> getAutoLoginResult() {
        return autoLoginResult;
    }

    public void login(String email, String password, boolean rememberMe) {
        new Thread(() -> {
            try {
                String jsonBody = "{\"email\":\"" + email + "\",\"password\":\"" + password + "\"}";
                String response = NetworkUtil.postRequest("https://reqres.in/api/login?api_key=reqres-free-v1", jsonBody);

                JSONObject jsonResponse = new JSONObject(response);
                if (jsonResponse.has("token")) {
                    // 登录成功
                    if (rememberMe) {
                        // 保存自动登录信息
                        sharedPreferences.edit()
                                .putString("autoLoginToken", jsonResponse.getString("token"))
                                .putString("autoLoginEmail", email)
                                .putBoolean("autoLoginEnabled", true)
                                .apply();
                    } else {
                        // 清除自动登录信息
                        sharedPreferences.edit()
                                .remove("autoLoginToken")
                                .remove("autoLoginEmail")
                                .putBoolean("autoLoginEnabled", false)
                                .apply();
                    }
                    loginResult.postValue("success");
                } else if (jsonResponse.has("error")) {
                    loginResult.postValue("error:" + jsonResponse.getString("error"));
                } else {
                    loginResult.postValue("error:登录失败");
                }
            } catch (Exception e) {
                loginResult.postValue("error:" + e.getMessage());
            }
        }).start();
    }

    // AuthViewModel.java - 修改register方法
    public void register(String email, String password) {
        new Thread(() -> {
            try {
                String jsonBody = "{\"email\":\"" + email + "\",\"password\":\"" + password + "\"}";
                String response = NetworkUtil.postRequest("https://reqres.in/api/register?api_key=reqres-free-v1", jsonBody);

                JSONObject jsonResponse = new JSONObject(response);
                if (jsonResponse.has("token")) {
                    // 注册成功，但不设置自动登录状态
                    // 只保存token用于当前会话，不启用自动登录
                    sharedPreferences.edit()
                            .putString("autoLoginToken", jsonResponse.getString("token"))
                            .putString("autoLoginEmail", email)
                            .putBoolean("autoLoginEnabled", false)  // 明确设置为false
                            .apply();
                    registerResult.postValue("success");
                } else if (jsonResponse.has("error")) {
                    registerResult.postValue("error:" + jsonResponse.getString("error"));
                } else {
                    registerResult.postValue("error:注册失败");
                }
            } catch (Exception e) {
                registerResult.postValue("error:" + e.getMessage());
            }
        }).start();
    }

    public void autoLogin() {
        new Thread(() -> {
            try {
                String token = sharedPreferences.getString("autoLoginToken", "");
                if (token.isEmpty()) {
                    autoLoginResult.postValue("error:无保存的登录信息");
                    return;
                }

                String response = NetworkUtil.getRequest("https://reqres.in/api/auto-login?api_key=reqres-free-v1");
                JSONObject jsonResponse = new JSONObject(response);

                if (jsonResponse.has("data")) {
                    autoLoginResult.postValue("success");
                } else {
                    autoLoginResult.postValue("error:自动登录失败");
                }
            } catch (Exception e) {
                autoLoginResult.postValue("error:" + e.getMessage());
            }
        }).start();
    }

    public boolean isAutoLoginEnabled() {
        return sharedPreferences.getBoolean("autoLoginEnabled", false);
    }
}